package com.wms.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wms.common.core.domain.model.LoginUser;
import com.wms.common.exception.ServiceException;
import com.wms.common.utils.SecurityUtils;
import com.wms.common.utils.StringUtils;
import com.wms.system.domain.SysRouteIndividuationConfig;
import com.wms.system.domain.SysRouteSearchConfig;
import com.wms.system.domain.SysTableConfig;
import com.wms.system.domain.SysTableConfigMultilingual;
import com.wms.system.domain.po.SysTableConfigPo;
import com.wms.system.domain.vo.QueryTableLabelConfigVo;
import com.wms.system.domain.vo.SysTableConfigVo;
import com.wms.system.mapper.SysRouteIndividuationConfigMapper;
import com.wms.system.mapper.SysRouteSearchConfigMapper;
import com.wms.system.mapper.SysTableConfigMapper;
import com.wms.system.mapper.SysTableConfigMultilingualMapper;
import com.wms.system.service.ISysTableConfigService;
import io.swagger.annotations.ApiModelProperty;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.util.List;

@Service
@RequiredArgsConstructor
public class SysTableConfigServiceImpl implements ISysTableConfigService {

    private final SysTableConfigMapper tableConfigMapper;

    private final SysTableConfigMultilingualMapper tableConfigMultilingualMapper;

    private final SysRouteIndividuationConfigMapper routeIndividuationConfigMapper;

    private final SysRouteSearchConfigMapper routeSearchConfigMapper;

    @Override
    public List<SysTableConfig> getTableConfigList(SysTableConfigVo tableConfigVo) {
        QueryWrapper<SysTableConfig> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(tableConfigVo.getLabel())) {
            queryWrapper.eq("label", tableConfigVo.getLabel());
        }
        if (StringUtils.isNotEmpty(tableConfigVo.getUrl())) {
            queryWrapper.like("url", tableConfigVo.getUrl());
        }
        if (StringUtils.isNotEmpty(tableConfigVo.getProp())) {
            queryWrapper.eq("prop", tableConfigVo.getProp());
        }
        return tableConfigMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void initialization(SysTableConfigVo tableConfigVo) {
        //记录数量用于排序
        int i = 0;
        Class<?> clazz = null;
        try {
            clazz = Class.forName(tableConfigVo.getClassName());
            Field[] declaredFields = clazz.getDeclaredFields();

            //先父类c
            Class<?> superclass = clazz.getSuperclass();
            System.out.println("父，名字：" + superclass.getName());
            Field[] superclassDeclaredFields = superclass.getDeclaredFields();
            for (Field field : superclassDeclaredFields) {
                SysTableConfig tableConfig = new SysTableConfig();
                tableConfig.setProp(field.getName());
                ApiModelProperty apiModelProperty =
                        field.getAnnotation(ApiModelProperty.class);
                if (apiModelProperty != null && !apiModelProperty.hidden()) {
                    tableConfig.setLabel(apiModelProperty.value());
                } else {
                    tableConfig.setLabel(field.getName());
                }
                tableConfig.setSort(i + 1);
                tableConfig.setUrl(tableConfigVo.getUrl());
                i += 1;
                tableConfigMapper.insert(tableConfig);
            }

            //再子类
            for (Field field : declaredFields) {
                SysTableConfig tableConfig = new SysTableConfig();
                tableConfig.setProp(field.getName());
                ApiModelProperty apiModelProperty =
                        field.getAnnotation(ApiModelProperty.class);
                if (apiModelProperty != null && !apiModelProperty.hidden()) {
                    tableConfig.setLabel(apiModelProperty.value());
                } else {
                    tableConfig.setLabel(field.getName());
                }
                tableConfig.setSort(i + 1);
                tableConfig.setUrl(tableConfigVo.getUrl());
                i += 1;
                tableConfigMapper.insert(tableConfig);
            }


        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void del(String id) {
        tableConfigMapper.deleteById(Long.parseLong(id));
    }

    @Override
    public void edit(SysTableConfigVo sysTableConfigVo) {
        if (StringUtils.isEmpty(sysTableConfigVo.getId())) {
            throw new ServiceException("id不能为空！");
        }
        SysTableConfig sysTableConfig = new SysTableConfig();
        BeanUtils.copyProperties(sysTableConfigVo, sysTableConfig);
        sysTableConfig.setId(Long.parseLong(sysTableConfigVo.getId()));
        tableConfigMapper.updateById(sysTableConfig);
    }

    @Override
    public List<SysTableConfigMultilingual> getMultilingual(String id) {
        QueryWrapper<SysTableConfigMultilingual> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("table_config_id", Long.parseLong(id));
        return tableConfigMultilingualMapper.selectList(queryWrapper);
    }

    @Override
    public void editMultilingual(SysTableConfigMultilingual sysTableConfigMultilingual) {
        tableConfigMultilingualMapper.updateById(sysTableConfigMultilingual);
    }

    @Override
    public void addMultilingual(SysTableConfigMultilingual sysTableConfigMultilingual) {
        tableConfigMultilingualMapper.insert(sysTableConfigMultilingual);
    }

    @Override
    public List<SysTableConfigPo> getTableLabelConfig(QueryTableLabelConfigVo configVo) {
        List<SysTableConfigPo> configPos = tableConfigMapper.getTableLabelConfig(configVo);
        if (!configPos.isEmpty()) {
            for (SysTableConfigPo configPo : configPos) {
                if (StringUtils.isNotEmpty(configPo.getLabelDescribe())) {
                    configPo.setLabel(configPo.getLabelDescribe());
                }
            }
        }
        return configPos;
    }

    @Override
    public void addRouteIndividuation(SysRouteIndividuationConfig individuationConfig) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        individuationConfig.setUserId(loginUser.getUserId());

        routeIndividuationConfigMapper.insert(individuationConfig);
    }

    @Override
    public void saveRouteIndividuation(SysRouteIndividuationConfig individuationConfig) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        QueryWrapper<SysRouteIndividuationConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", loginUser.getUserId());
        queryWrapper.eq("url", individuationConfig.getUrl());
        List<SysRouteIndividuationConfig> individuationConfigs = routeIndividuationConfigMapper.selectList(queryWrapper);
        if (individuationConfigs.isEmpty()) {
            individuationConfig.setUserId(loginUser.getUserId());
            routeIndividuationConfigMapper.insert(individuationConfig);
        } else {
            SysRouteIndividuationConfig config = individuationConfigs.get(0);
            config.setIndividuation(individuationConfig.getIndividuation());
            routeIndividuationConfigMapper.updateById(config);
        }


    }

    @Override
    public SysRouteIndividuationConfig getIndividuation(SysRouteIndividuationConfig individuationConfig) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        QueryWrapper<SysRouteIndividuationConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", loginUser.getUserId());
        queryWrapper.eq("url", individuationConfig.getUrl());
        List<SysRouteIndividuationConfig> individuationConfigs = routeIndividuationConfigMapper.selectList(queryWrapper);
        if (individuationConfigs.isEmpty()) {
            return new SysRouteIndividuationConfig();
        }
        return individuationConfigs.get(0);
    }

    @Override
    public void tableConfigAdd(SysTableConfig tableConfigVo) {
        tableConfigMapper.insert(tableConfigVo);
    }

    @Override
    public void saveRouteSearch(SysRouteSearchConfig searchConfig) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        QueryWrapper<SysRouteSearchConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", loginUser.getUserId());
        queryWrapper.eq("url", searchConfig.getUrl());
        List<SysRouteSearchConfig> individuationConfigs = routeSearchConfigMapper.selectList(queryWrapper);
        if (individuationConfigs.isEmpty()) {
            searchConfig.setUserId(loginUser.getUserId());
            routeSearchConfigMapper.insert(searchConfig);
        } else {
            SysRouteSearchConfig config = individuationConfigs.get(0);
            config.setIndividuation(searchConfig.getIndividuation());
            routeSearchConfigMapper.updateById(config);
        }
    }

    @Override
    public SysRouteSearchConfig getRouteSearch(SysRouteSearchConfig searchConfig) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        QueryWrapper<SysRouteSearchConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", loginUser.getUserId());
        queryWrapper.eq("url", searchConfig.getUrl());
        List<SysRouteSearchConfig> search = routeSearchConfigMapper.selectList(queryWrapper);
        if (search.isEmpty()) {
            return new SysRouteSearchConfig();
        }
        return search.get(0);
    }

    public static void main(String[] args) {
        String url = "com.wms.system.domain.vo.";
        Class<?> clazz = null;
        try {
            clazz = Class.forName(url + "SysTableConfigVo");
            Field[] declaredFields = clazz.getDeclaredFields();
            for (Field field : declaredFields) {
                System.out.println("prop:" + field.getName());
                ApiModelProperty apiModelProperty =
                        field.getAnnotation(ApiModelProperty.class);
                if (apiModelProperty != null && !apiModelProperty.hidden()) {
                    System.out.println("label:" + apiModelProperty.value());
                }
            }

            Class<?> superclass = clazz.getSuperclass();
            System.out.println("父，名字：" + superclass.getName());
            Field[] superclassDeclaredFields = superclass.getDeclaredFields();
            for (Field field : superclassDeclaredFields) {
                System.out.println("prop:" + field.getName());
                ApiModelProperty apiModelProperty =
                        field.getAnnotation(ApiModelProperty.class);
                if (apiModelProperty != null && !apiModelProperty.hidden()) {
                    System.out.println("label:" + apiModelProperty.value());
                }
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }


//        Field[] declaredFields = InventoryManageVo.class.getDeclaredFields();
//        StringBuffer buf = new StringBuffer();
//        for (int i = 0; i < declaredFields.length; i++) {
//            Field field = declaredFields[i];
//            String fieldName = field.getName();
//            //TODO相同的逻辑走一遍
//            ApiModelProperty apiModelProperty =
//                    field.getAnnotation(ApiModelProperty.class);
//            if (apiModelProperty != null && !apiModelProperty.hidden()) {
//                String str = fieldName + "\":" + "\"" + apiModelProperty.value();
//                buf.append(str);
//            }
//        }
//        System.out.println(buf.toString());
    }
}
